//
//  MKUserAccountViewModel.swift
//  MKWeiBo2017
//
//  Created by nicolas on 2017/7/3.
//  Copyright © 2017年 nicolas. All rights reserved.
//

import UIKit

class MKUserAccountViewModel: NSObject {
    
    static let sharedInstance: MKUserAccountViewModel = MKUserAccountViewModel()
    
    let userAccountPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/account.plist"
    
    var userAccount: MKUserAccount?
    
    /// 用户是否登录的属性
    var isUserLogin: Bool {
        get {
            return userAccount != nil   // 账号!=nil就表示登录了
        }
    }
    
    override init() {
        
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    func loadAccessToken(code: String,callback:@escaping (_ error:NSError?) -> ()) {
        
        let urlString = "oauth2/access_token"
        
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":redirect_uri
        ]
        
        MKNetworkingTool.sharedInstance.request(method: RequestMethod.POST, URLString: urlString, parameters: parameters as AnyObject, success: { (task, responseObject) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                let userAccount = MKUserAccount(dict: result)
                
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
                self.userAccount = userAccount
                MKPrint(items: "userAccount:\(userAccount)")

                callback(nil)
                
            }else {
                
                MKPrint(items: "返回数据转字典失败")
            }
            
            }, failure: { (task, error) in
                MKPrint(items: "\(error)")
                callback(error as NSError?)
        })
    }
    
    // 保存账号到沙盒中
    private func saveUserAccount() {
        // 调用归档的方法,将模型归档到沙盒里面
        // 让userAccount对象保存到self.userAccountPath这个路径
        if let account = userAccount {
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        }
    }
    
    // 解档账号
    func loadUserAccount() -> MKUserAccount? {
     
        if let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: self.userAccountPath) as? MKUserAccount {
            
            if userAccount.expiresDate?.compare(NSDate() as Date) != ComparisonResult.orderedAscending {
                MKPrint(items: "没有过期")
                return userAccount
            }else {
                return nil;
            }
            
        }else {
            return nil
        }
    }
    
    func loadUserInfo(loadUserInfoCallback:() -> ()) {
        
        // 可选绑定会造成嵌套层次很多, swift提供了另外一种形式,守卫 guard
        // guard正好相反
        guard let access_token = userAccount?.access_token else {
            // 能到里面来说明access_token没有值
            MKPrint(items: "access_token没有值")
            return
        }
        // access_token有值可以在后面继续使用
        guard let uid = userAccount?.uid else {
            // 能到这里面来说明uid没有值
            MKPrint(items: "uid没有值")
            return
        }
        // uid有值,可以在后面使用uid
        // urlString
        let urlString = "2/users/show.json"
        
        // 参数
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        // 发送请求
        MKNetworkingTool.sharedInstance.request(method: RequestMethod.GET, URLString: urlString, parameters: parameters as AnyObject, success: { (_, responseObject) -> Void in
            //            CZPrint(items: "获取用户信息: \(responseObject)")
            if let result = responseObject as? [String: AnyObject] {
                // 只需要用户的名称和头像地址
                let screen_name = result["screen_name"] as? String
                
                let avatar_large = result["avatar_large"] as? String
                
                // 赋值到当前账号的模型中
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                
                // 将userAccount保存到沙盒中
                self.saveUserAccount()
            }
        }) { (_, error) -> Void in
            MKPrint(items: "获取用户信息出错了: \(error)")
        }
    }
}
